﻿using BZ.Core.TaskExt;
using NDK.LocalUtils;
using NDK.Motion.Sys;
using NDK.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NDK.Module.Model.ACMTMUR
{

    public class MURMES : Upload
    {
        private static log4net.ILog m_Logger = log4net.LogManager.GetLogger("MURMESLogger");
        public MURMesConfig Config { get; set; }
        public ConcurrentQueue<MURMesInfo> MURMESQueue { get; set; }

        public MURMES ()
        {
            MURMESQueue = new ConcurrentQueue<MURMesInfo>();
            Config = SerializeUtils.XmlDeserialize<MURMesConfig>($@"{Application.StartupPath}\Config\MURMES\MesConfig.xml");
            MachineStatusManager.PropertyChanged += MachineStatusManager_PropertyChanged;
        }

        private void MachineStatusManager_PropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if(Common.isUploadMes)
            {
                Task.Run(() =>
                {
                    string status = string.Empty, model = "01";
                    switch(MachineStatusManager.CurrentMachineStatus)
                    {
                        case MachineStatus.Manual:
                            status = "01";
                            break;
                        case MachineStatus.Auto:
                            status = "10";
                            break;
                        case MachineStatus.Running:
                            status = "02";
                            break;
                        case MachineStatus.Pause:
                        case MachineStatus.Stopping:
                            status = "08";
                            break;
                        case MachineStatus.Alarm:
                            break;
                        case MachineStatus.Emerg:
                            status = "20";
                            break;
                        case MachineStatus.Ready:
                            status = "04";
                            break;
                    }
                    if(status != string.Empty)
                    {
                        string re1 = Send(MesType.RunStatus, status, model, null, null, null);
                        m_Logger.Info($"接收{MesType.RunStatus}:{re1}\r\n");
                    }
                });
            }
        }

        public string Send (MesType type, string runStatus, string runMode, string troubleAlarmCode, string lotNo, string defectCode, MURRowData rowDatas = null)
        {
            MURMesInfo info = new MURMesInfo(Config, type)
            {
                Timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"),
                MdlCode = Common.MES_MdlCode,
                RunStatus = runStatus,
                RunMode = runMode,
                TroubleAlarmCode = troubleAlarmCode,
                LotNo = lotNo,
                DefectCode = defectCode,
                RowDatas = rowDatas,
                Remarks = "FAI1,FAI29,FAI40,FAI33_MAX"
            };
            m_Logger.Info($"发送{type}:{info}\r\n");
            return PostAndGet(Config.URL, info.ToString());
        }

        object obj = new object();
        public void UpLoadMURMES ()
        {
            lock (obj)
            {
                try
                {
                    while(MURMESQueue.Count > 0)
                    {
                        MURMESQueue.TryDequeue(out var queue);
                        m_Logger.Info($"发送{queue.Type}:{queue}\r\n");
                        string result = PostAndGet(Config.URL, queue.ToString());
                        m_Logger.Info($"接收{queue.Type}:{result}\r\n");

                        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                        if(dic["ResultCode"] != "0")
                        {
                            Common.AppendUiLog.Log("MES上传失败！", BZ.Logger.LogType.Error);
                            MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                        }
                        else
                        {
                            Common.AppendUiLog.Log("MES上传成功！", BZ.Logger.LogType.Alert);
                        }
                    }
                }
                catch(Exception ex)
                {
                    m_Logger.Info($"MES上传异常！原因:{ex.Message}");
                }
            }
        }
    }
}
